package com.spring.demo5.eg2;


import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;

import java.util.Map;

/**
 * @author vhans
 */
// 当IService类型的bean不存在时才注入
public class OnMissingBeanCondition implements Condition {
    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        // 获取bean工厂
        ConfigurableListableBeanFactory beanFactory = conditionContext.getBeanFactory();
        // 从容器中获取IService类型的bean
        assert beanFactory != null;
        Map<String, IService> serviceMap = beanFactory.getBeansOfType(IService.class);
        // 判断serviceMap是否为空,为空则进行注入
        return serviceMap.isEmpty();
    }
}
